<!DOCTYPE html><html lang="[&quot;zh-Hans&quot;,&quot;zh-CN&quot;,&quot;default&quot;]"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="动态更改keyframes"><meta name="keywords" content="JavaScript"><meta name="author" content="wenmu"><meta name="copyright" content="wenmu"><title>动态更改keyframes | 温木的博客</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.6.1"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.6.1"><link rel="dns-prefetch" href="https://cdn.staticfile.org"><link rel="dns-prefetch" href="https://cdn.bootcss.com"><link rel="dns-prefetch" href="https://creativecommons.org"><link rel="dns-prefetch" href="http://ta.qq.com"><script>(function() {
   var hm = document.createElement("script");
   hm.src = "https://tajs.qq.com/stats?sId=&lt;script type=&quot;text/javascript&quot; src=&quot;http://tajs.qq.com/stats?sId=66523541&quot; charset=&quot;UTF-8&quot;&gt;&lt;/script&gt;";
   var s = document.getElementsByTagName("script")[0];
   s.parentNode.insertBefore(hm, s);
 })();</script><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  }
} </script><meta name="generator" content="Hexo 4.2.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#背景"><span class="toc-number">1.</span> <span class="toc-text">背景</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#思路"><span class="toc-number">2.</span> <span class="toc-text">思路</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#动态更改-keyframes"><span class="toc-number">3.</span> <span class="toc-text">动态更改@keyframes</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#styleSheets-分内部和外部样式"><span class="toc-number">4.</span> <span class="toc-text">styleSheets 分内部和外部样式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#通过属性设置animation-name属性"><span class="toc-number">5.</span> <span class="toc-text">通过属性设置animation-name属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#动态设置-keyframes"><span class="toc-number">6.</span> <span class="toc-text">动态设置 keyframes</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#最终解决方案"><span class="toc-number">7.</span> <span class="toc-text">最终解决方案</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="https://i.loli.net/2020/02/27/xwaBoOj158MfNyq.jpg"></div><div class="author-info__name text-center">wenmu</div><div class="author-info__description text-center">记录一些在工作中或学习新知识时学到的一些知识点；正所谓好记性不如一个烂笔头，温故而知新！</div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">115</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">52</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">分类</span><span class="pull-right">30</span></a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">温木的博客</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus"><a class="site-page" href="/">首页</a><a class="site-page" href="/archives">文章</a><a class="site-page" href="/tags">标签</a><a class="site-page" href="/categories">分类</a></span></div><div id="post-info"><div id="post-title">动态更改keyframes</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2020-06-19</time><span class="post-meta__separator">|</span><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/JavaScript/">JavaScript</a></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><h2 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h2><p>最近做了一个上线滚动文字的走马灯组件，通过关键帧@keyframes at-rule 来定义滚动；<br>由于我的滚动条目是动态的，个数不定，所以需要动态计算时间段显示的内容。</p>
<h2 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h2><p>就是@keyframe 设置在不同时间显示不同的元素，通过绝对定位来实现，动态控制元素的位置来控制显示哪个元素。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">div</span> &#123;</span><br><span class="line">  <span class="attribute">animation</span>: myfirst <span class="number">5s</span>;</span><br><span class="line">  animation-iteration-count: infinite; // 无限循环</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">@keyframes</span> myfirst &#123;</span><br><span class="line">  0% &#123;</span><br><span class="line">    <span class="attribute">left</span>: <span class="number">0</span>;</span><br><span class="line">    <span class="attribute">top</span>: <span class="number">0</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  ,</span><br><span class="line">  25% &#123;</span><br><span class="line">    <span class="attribute">left</span>: <span class="number">0</span>;</span><br><span class="line">    <span class="attribute">top</span>: -<span class="number">24px</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  50% &#123;</span><br><span class="line">    <span class="attribute">left</span>: <span class="number">0</span>;</span><br><span class="line">    <span class="attribute">top</span>: -<span class="number">48px</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  100% &#123;</span><br><span class="line">    <span class="attribute">left</span>: <span class="number">0</span>;</span><br><span class="line">    <span class="attribute">top</span>: -<span class="number">72px</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 兼容性的代码省略</span><br></pre></td></tr></table></figure>

<p>上面是基本的代码，但是我的条目是动态的，所以时间刻度需要动态计算，但是@keyframe 没有像元素样式的动态的属性，不能计算后赋值给元素； 在网上的查询后，最终使用动态给样式对象插入新的样式的方式来实现。</p>
<h2 id="动态更改-keyframes"><a href="#动态更改-keyframes" class="headerlink" title="动态更改@keyframes"></a>动态更改@keyframes</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> styleSheet = <span class="built_in">document</span>.styleSheets[<span class="number">0</span>];</span><br><span class="line">styleSheet.insertRule(<span class="string">"keyframe的定义"</span>, <span class="number">3</span>);</span><br></pre></td></tr></table></figure>

<p>网上的大致思路就是上面的代码，但是有几个坑。</p>
<h2 id="styleSheets-分内部和外部样式"><a href="#styleSheets-分内部和外部样式" class="headerlink" title="styleSheets 分内部和外部样式"></a>styleSheets 分内部和外部样式</h2><p>我在写 demo 测试的时候，由于我没有内嵌样式，所以看到的都是外部，所以我就把样式插入到了第一个里面，但是放到项目里面发现，竟然报错提示没有<code>rules</code>属性。因为如果有内嵌样式，第一个是内嵌样式，内嵌的 rules 属性是没有值的。所以为了保险不要直接在第一个对象中插入。最好插入到最后一个</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> styleSheet = <span class="built_in">document</span>.styleSheets[<span class="built_in">document</span>.styleSheets.length - <span class="number">1</span>];</span><br></pre></td></tr></table></figure>

<h2 id="通过属性设置animation-name属性"><a href="#通过属性设置animation-name属性" class="headerlink" title="通过属性设置animation-name属性"></a>通过属性设置<code>animation-name</code>属性</h2><p>开始我是按照网上的写法，直接设置 animation 属性</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">animation</span>: <span class="selector-tag">myfirst</span> 5<span class="selector-tag">s</span>;</span><br></pre></td></tr></table></figure>

<p>由于我是 react，使用了 webpack 打包，打包后，名字<code>myfirst</code>被重新命名了。由于 demo 中的样式比价少，可以通过<code>document.styleSheets</code>看到，样式中 myfirst 被打包后的名字；并且也可以看到它的位置。<br>但是在项目中，样式比较多，根据打包后的名字去设置比较困难的</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> styleSheet = <span class="built_in">document</span>.styleSheets[<span class="built_in">document</span>.styleSheets.length - <span class="number">1</span>];</span><br><span class="line"><span class="keyword">const</span> keyframesName = styleSheet.rules[<span class="number">0</span>].name;</span><br><span class="line"><span class="keyword">const</span> keyframesStr = <span class="string">`<span class="subst">$&#123;keyframesName&#125;</span> &#123;0% &#123;</span></span><br><span class="line"><span class="string">          left: 0px;</span></span><br><span class="line"><span class="string">          top: 0px;</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">        <span class="subst">$&#123;keyframesItem.join(<span class="string">""</span>)&#125;</span></span></span><br><span class="line"><span class="string">      &#125;`</span>.replace(<span class="regexp">/\s+/g</span>, <span class="string">""</span>);</span><br><span class="line"><span class="keyword">const</span> keyframes = <span class="string">`@keyframes <span class="subst">$&#123;keyframesStr&#125;</span>`</span>;</span><br><span class="line"><span class="keyword">const</span> keyframes_webdit = <span class="string">`@-webkit-keyframes <span class="subst">$&#123;keyframesStr&#125;</span>`</span>; <span class="comment">/* Safari 和 Chrome */</span></span><br><span class="line"></span><br><span class="line">styleSheet.insertRule(keyframes, styleSheet.rules.length);</span><br><span class="line">styleSheet.insertRule(keyframes_webdit, styleSheet.rules.length);</span><br></pre></td></tr></table></figure>

<h2 id="动态设置-keyframes"><a href="#动态设置-keyframes" class="headerlink" title="动态设置 keyframes"></a>动态设置 keyframes</h2><p>这个需要用到<code>insertRule()</code>方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">styleSheet.insertRule(keyframes_webdit, styleSheet.rules.length);</span><br></pre></td></tr></table></figure>

<h2 id="最终解决方案"><a href="#最终解决方案" class="headerlink" title="最终解决方案"></a>最终解决方案</h2><ul>
<li>在样式中不指定 animation-name,通过 js 操作样式属性设置，这样生成 keyframes 时，就不用去获取打包生成的名字。</li>
<li>样式直接插入最后的 styleSheets 中</li>
<li>在 js 中指定<code>animationName</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 在全局定义名字</span></span><br><span class="line"><span class="keyword">const</span> keyframesName = <span class="string">"text-carousel-keyframesName-key-asdf8324-df324s"</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 关键代码</span></span><br><span class="line"><span class="keyword">const</span> styleSheet = <span class="built_in">document</span>.styleSheets[<span class="built_in">document</span>.styleSheets.length - <span class="number">1</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> keyframesStr = <span class="string">`<span class="subst">$&#123;keyframesName&#125;</span> &#123;0% &#123;</span></span><br><span class="line"><span class="string">          left: 0px;</span></span><br><span class="line"><span class="string">          top: 0px;</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">        <span class="subst">$&#123;keyframesItem.join(<span class="string">""</span>)&#125;</span></span></span><br><span class="line"><span class="string">      &#125;`</span>.replace(<span class="regexp">/\s+/g</span>, <span class="string">""</span>);</span><br><span class="line"><span class="keyword">const</span> keyframes = <span class="string">`@keyframes <span class="subst">$&#123;keyframesStr&#125;</span>`</span>;</span><br><span class="line"><span class="keyword">const</span> keyframes_webdit = <span class="string">`@-webkit-keyframes <span class="subst">$&#123;keyframesStr&#125;</span>`</span>; <span class="comment">/* Safari 和 Chrome */</span></span><br><span class="line"></span><br><span class="line">styleSheet.insertRule(keyframes, styleSheet.rules.length);</span><br><span class="line">styleSheet.insertRule(keyframes_webdit, styleSheet.rules.length);</span><br><span class="line"></span><br><span class="line"><span class="comment">// jsx</span></span><br><span class="line"></span><br><span class="line"> &lt;section</span><br><span class="line">          className=&#123;styles.itemContainer&#125;</span><br><span class="line">          style=&#123;&#123;</span><br><span class="line">            animationDuration: animationDuration,</span><br><span class="line">            animationName: keyframesName,   <span class="comment">// 设置名字</span></span><br><span class="line">            ...contentStyle,</span><br><span class="line">          &#125;&#125;</span><br><span class="line">        &gt;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">wenmu</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://blog.wangpengpeng.site/2020/06/19/%E5%8A%A8%E6%80%81%E6%9B%B4%E6%94%B9keyframes/">http://blog.wangpengpeng.site/2020/06/19/%E5%8A%A8%E6%80%81%E6%9B%B4%E6%94%B9keyframes/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://blog.wangpengpeng.site">温木的博客</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JavaScript/">JavaScript</a></div><div class="post-qr-code"><div class="post-qr-code-item"><img class="post-qr-code__img" src="https://i.loli.net/2020/02/27/hOBzIxFDJMCrmtN.jpg"><div class="post-qr-code__desc">微信打赏</div></div></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2020/06/19/js%E5%88%A4%E6%96%AD%E6%B5%8F%E8%A7%88%E5%99%A8%E7%AA%97%E5%8F%A3%E7%9A%84%E5%85%B3%E9%97%AD%E4%B8%8E%E5%88%B7%E6%96%B0/"><i class="fa fa-chevron-left">  </i><span>js判断浏览器窗口的关闭与刷新</span></a></div><div class="next-post pull-right"><a href="/2020/06/11/node-parentNode%E5%92%8Cnode-parentElement%E7%9A%84%E5%8C%BA%E5%88%AB/"><span>node.parentNode和node.parentElement的区别</span><i class="fa fa-chevron-right"></i></a></div></nav><div id="vcomment"></div><script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script><script src="https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js"></script><script>var notify = 'false' == true ? true : false;
var verify = 'false' == true ? true : false;
var GUEST_INFO = ['nick','mail','link'];
var guest_info = 'nick,mail,link'.split(',').filter(function(item){
  return GUEST_INFO.indexOf(item) > -1
});
guest_info = guest_info.length == 0 ? GUEST_INFO :guest_info;
window.valine = new Valine({
  el:'#vcomment',
  notify:notify,
  verify:verify,
  appId:'U1QqpeQNuBnRsfygHk1GQ30q-gzGzoHsz',
  appKey:'dunDQzEseDzgsKgw4qLQcog1',
  placeholder:'支持markdown！',
  avatar:'wavatar',
  guest_info:guest_info,
  pageSize:'20',
  lang: 'zh-cn'
})</script></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2019 - 2020 By wenmu</div><div class="framework-info"><span>驱动 - </span><a href="http://hexo.io" target="_blank" rel="noopener"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a href="https://github.com/Molunerfinn/hexo-theme-melody" target="_blank" rel="noopener"><span>Melody</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv">该文访问量<span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.6.1"></script><script src="/js/fancybox.js?version=1.6.1"></script><script src="/js/sidebar.js?version=1.6.1"></script><script src="/js/copy.js?version=1.6.1"></script><script src="/js/fireworks.js?version=1.6.1"></script><script src="/js/transition.js?version=1.6.1"></script><script src="/js/scroll.js?version=1.6.1"></script><script src="/js/head.js?version=1.6.1"></script><script>if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
}</script></body></html>